package org.csu.jpetstore.controller;

import jakarta.servlet.http.HttpSession;
import org.csu.jpetstore.domain.Account;
import org.csu.jpetstore.domain.Order;
import org.csu.jpetstore.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping("/order")
@SessionAttributes(names = {"orders","orderToShow"})
public class OrderController {
    @Autowired
    private OrderService orderService;

    @GetMapping("/api/param/getOrder")
    public Order getOrder(@RequestParam int orderId){
        return orderService.getOrder(orderId);
    }

    @PostMapping("/api/param/updateOrderById")
    @Transactional
    public void updateOrderById(@RequestParam int orderId,@RequestParam Order order){
        orderService.updateOrderById(orderId,order);
    }

    @GetMapping("/api/param/getOrders")
    public List<Order> getOrders(){
        return orderService.getOrders();
    }

    @GetMapping("/api/suggestions")
    @ResponseBody
    public List<String> getUsernameSuggestions(@RequestParam String query) {
        List<Order> allOrders = orderService.getOrders();
        Set<String> suggestions = new HashSet<>();
        
        for (Order order : allOrders) {
            if (order.getUserId().toLowerCase().contains(query.toLowerCase())) {
                suggestions.add(order.getUserId());
            }
        }
        
        return new ArrayList<>(suggestions);
    }

    @GetMapping("/api/param/getOrdersByUserID")
    public List<Order> getOrdersByUserID(@RequestParam String userID){
        return orderService.getOrdersByUserID(userID);
    }

    @PostMapping("/api/param/updateOrderStatusById")
    @Transactional
    public void updateOrderStatusById(@PathVariable int ordersID,
                                @RequestParam String username){
        orderService.updateOrderStatusById(ordersID,username);
    }

    @PostMapping("/api/param/addOrder")
    public void addOrder(@PathVariable Order order){
        orderService.addOrder(order);
    }




    @GetMapping("/view")
    public String viewOrder(Model model){
        //实际上应从数据库获取orders
        List<Order> orders = getOrders();
        model.addAttribute("orders",orders);

        return "order/order";
    }

    //搜索订单
    @GetMapping("/toFind")
    public  String searchOrder(){
        return "order/toFindOrder";
    }

    //查询订单
    @PostMapping("/find")
    public String findOrder(@RequestParam String keyword,Model model){
       List<Order> findOrders = getOrdersByUserID(keyword);

       model.addAttribute("orders",findOrders);

       return "order/order";
    }



    //修改订单前
    @GetMapping("/toRevise")
    public  String toReviseOrder(@RequestParam int orderId,Model model){
        //实际上从数据库，根据orderId查找修改前order相关数据
        Order orderToShow = getOrder(orderId);

        model.addAttribute("orderToShow",orderToShow);

        //将修改前数据显示在前端
        return "order/toReviseOrder";
    }

    //提交订单修改
    @PostMapping("/revise")
    public String reviseOrder(@RequestParam int orderId,
                              @RequestParam String userId,
                              @RequestParam BigDecimal totalPrice,
                              @RequestParam String cardType,
                              @RequestParam String cardNumber,
                              @RequestParam String billFirstName,
                              @RequestParam String billLastName,
                              @RequestParam String billAddr1,
                              @RequestParam String billAddr2,
                              @RequestParam String billCity,
                              @RequestParam String billState,
                              @RequestParam String billZip,
                              @RequestParam String billCountry,
                              Model model){
        //修改订单
        Order order = getOrder(orderId);
        order.setOrderId(orderId);
        order.setUserId(userId);
        order.setTotalPrice(totalPrice);
        order.setCardType(cardType);
        order.setCreditCard(cardNumber);
        order.setBillFirstName(billFirstName);
        order.setBillLastName(billLastName);
        order.setBillAddr1(billAddr1);
        order.setBillAddr2(billAddr2);
        order.setBillCity(billCity);
        order.setBillState(billState);
        order.setBillZip(billZip);
        order.setBillCountry(billCountry);
        updateOrderById(orderId,order);



        //完成修改后,传到会话的orderToShow
        List<Order> orders = (List<Order>) model.getAttribute("orders");
        if (orders == null){
            orders = getOrders();
        }
        int i = 0;
        while(orders.get(i).getOrderId() != orderId){
            i++;
        }
        orders.set(i,order);
        model.addAttribute("orders",orders);

        //修改完成跳回主页
        return "order/order";
    }

    //增加订单前
    @GetMapping("/toAdd")
    public  String toAddOrder(){
        return "order/toAddOrder";
    }

    //增加订单
    @PostMapping("/add")
    public String addOrder(@RequestParam String username,
                           @RequestParam BigDecimal totalPrice,
                           @RequestParam String cardType,
                           @RequestParam String cardNumber,
                           @RequestParam String billFirstName,
                           @RequestParam String billLastName,
                           @RequestParam String billAddr1,
                           @RequestParam String billAddr2,
                           @RequestParam String billCity,
                           @RequestParam String billState,
                           @RequestParam String billZip,
                           @RequestParam String billCountry,
                           Model model){
        //数据库插入
        List<Order> orders = (List<Order>) model.getAttribute("orders");
        if (orders == null){
            orders = getOrders();
        }
        Order order = new Order();
        order.setOrderId(orders.size()+1);
        order.setUserId(username);
        order.setOrderDate(new Date());
        order.setTotalPrice(totalPrice);
        order.setCardType(cardType);
        order.setCreditCard(cardNumber);
        order.setBillFirstName(billFirstName);
        order.setBillLastName(billLastName);
        order.setBillAddr1(billAddr1);
        order.setBillAddr2(billAddr2);
        order.setBillCity(billCity);
        order.setBillState(billState);
        order.setBillZip(billZip);
        order.setBillCountry(billCountry);

        order.setShipAddr1("0");
        order.setShipAddr2("0");
        order.setShipCity("0");
        order.setShipState("0");
        order.setShipZip("0");
        order.setShipCountry("0");
        order.setCourier("0");
        order.setExprDate("0");
        order.setFinished(false);
        order.setLocale("0");
        order.setShipToFirstName("0");
        order.setShipToLastName("0");

        addOrder(order);



        // 修改会话的orders
        orders.add(order);
        model.addAttribute("orders",orders);

        //返回主界面
        return "order/order";
    }

    //发货
    @GetMapping("/complete")
    public ResponseEntity<Map<String, Object>> completeOrder(
            @RequestParam int orderId,
            @RequestParam String username) {

        Map<String, Object> response = new HashMap<>();
        try {
            // 实际业务逻辑（示例）
            updateOrderStatusById(orderId, username);

            response.put("status", "success");
            response.put("message", "发货成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("status", "error");
            response.put("message", "发货失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

}